In this project, you will apply unsupervised learning techniques to identify segments of the population that form the core customer base for a mail-order sales company in Germany. These segments can then be used to direct marketing campaigns towards audiences that will have the highest expected rate of returns. The data that you will use has been provided by our partners at Bertelsmann Arvato Analytics, and represents a real-life data science task.
This notebook will help you complete this task by providing a framework within which you will perform your analysis steps. In each step of the project, you will see some text describing the subtask that you will perform, followed by one or more code cells for you to complete your work. Feel free to add additional code and markdown cells as you go along so that you can explore everything in precise chunks. The code cells provided in the base template will outline only the major tasks, and will usually not be enough to cover all of the minor tasks that comprise it.
It should be noted that while there will be precise guidelines on how you should handle certain tasks in the project, there will also be places where an exact specification is not provided. There will be times in the project where you will need to make and justify your own decisions on how to treat the data. These are places where there may not be only one way to handle the data. In real-life tasks, there may be many valid ways to approach an analysis task. One of the most important things you can do is clearly document your approach so that other scientists can understand the decisions you've made.
At the end of most sections, there will be a Markdown cell labeled Discussion. In these cells, you will report your findings for the completed section, as well as document the decisions that you made in your approach to each subtask. Your project will be evaluated not just on the code used to complete the tasks outlined, but also your communication about your observations and conclusions at each stage.
# import libraries here; add more as necessary
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# magic word for producing visualizations in notebook
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
from sklearn.preprocessing import Imputer, StandardScaler
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
np.random.seed(123)
'''
Import note: The classroom currently uses sklearn version 0.19.
If you need to use an imputer, it is available in sklearn.preprocessing.Imputer,
instead of sklearn.impute as in newer versions of sklearn.
'''
There are four files associated with this project (not including this one):
Udacity_AZDIAS_Subset.csv: Demographics data for the general population of Germany; 891211 persons (rows) x 85 features (columns).Udacity_CUSTOMERS_Subset.csv: Demographics data for customers of a mail-order company; 191652 persons (rows) x 85 features (columns).Data_Dictionary.md: Detailed information file about the features in the provided datasets.AZDIAS_Feature_Summary.csv: Summary of feature attributes for demographics data; 85 features (rows) x 4 columnsEach row of the demographics files represents a single person, but also includes information outside of individuals, including information about their household, building, and neighborhood. You will use this information to cluster the general population into groups with similar demographic properties. Then, you will see how the people in the customers dataset fit into those created clusters. The hope here is that certain clusters are over-represented in the customers data, as compared to the general population; those over-represented clusters will be assumed to be part of the core userbase. This information can then be used for further applications, such as targeting for a marketing campaign.
To start off with, load in the demographics data for the general population into a pandas DataFrame, and do the same for the feature attributes summary. Note for all of the .csv data files in this project: they're semicolon (;) delimited, so you'll need an additional argument in your read_csv() call to read in the data properly. Also, considering the size of the main dataset, it may take some time for it to load completely.
Once the dataset is loaded, it's recommended that you take a little bit of time just browsing the general structure of the dataset and feature summary file. You'll be getting deep into the innards of the cleaning in the first major step of the project, so gaining some general familiarity can help you get your bearings.
# Load in the general demographics data.
azdias = pd.read_csv('Udacity_AZDIAS_Subset.csv', sep = ';')
# Load in the feature summary file.
feat_info = pd.read_csv('AZDIAS_Feature_Summary.csv', sep = ';')
# Check the structure of the data after it's loaded (e.g. print the number of
# rows and columns, print the first few rows).
azdias.head()
feat_info.head()
Tip: Add additional cells to keep everything in reasonably-sized chunks! Keyboard shortcut
esc --> a(press escape to enter command mode, then press the 'A' key) adds a new cell before the active cell, andesc --> badds a new cell after the active cell. If you need to convert an active cell to a markdown cell, useesc --> mand to convert to a code cell, useesc --> y.
The feature summary file contains a summary of properties for each demographics data column. You will use this file to help you make cleaning decisions during this stage of the project. First of all, you should assess the demographics data in terms of missing data. Pay attention to the following points as you perform your analysis, and take notes on what you observe. Make sure that you fill in the Discussion cell with your findings and decisions at the end of each step that has one!
The fourth column of the feature attributes summary (loaded in above as feat_info) documents the codes from the data dictionary that indicate missing or unknown data. While the file encodes this as a list (e.g. [-1,0]), this will get read in as a string object. You'll need to do a little bit of parsing to make use of it to identify and clean the data. Convert data that matches a 'missing' or 'unknown' value code into a numpy NaN value. You might want to see how much data takes on a 'missing' or 'unknown' code, and how much data is naturally missing, as a point of interest.
As one more reminder, you are encouraged to add additional cells to break up your analysis into manageable chunks.
#Sample some columns to check the composition of data
print(azdias['PLZ8_HHZ'].unique())
print(azdias['PLZ8_BAUMAX'].unique())
print(azdias['CJT_GESAMTTYP'].unique())
print(azdias['ARBEIT'].unique())
print(azdias['CAMEO_DEU_2015'].unique())
azdias.isnull().sum().to_frame(name = 'missing_count').head(30)
From the column sampling, we can tell that besides assigned missing values in the data dictionary, a column can still contain nan. In addition, not all missing values in data dictionary exist in a column.
columns = azdias.columns
columns
# Identify missing or unknown data values and convert them to NaNs.
def convert_missing(df):
'''
Change the values that represent missing values in data dictionary to nan
'''
for col in columns:
missing = feat_info[feat_info['attribute'] == col]['missing_or_unknown']
#change the panda series into a string
missing_str = missing.to_string(index = False).strip('[]')
if missing_str != '':
#change the string into a list
missing_list =[x if x in ['X','XX'] else int(x) for x in missing_str.split(',')]
#replace missing values in missing_list with nan
df[col] = df[col].replace(missing_list, np.nan)
return df
azdias = convert_missing(azdias)
#verification of the function convert_missing
print(azdias['ARBEIT'].unique())
print(azdias['CAMEO_DEU_2015'].unique())
How much missing data is present in each column? There are a few columns that are outliers in terms of the proportion of values that are missing. You will want to use matplotlib's hist() function to visualize the distribution of missing value counts to find these columns. Identify and document these columns. While some of these columns might have justifications for keeping or re-encoding the data, for this project you should just remove them from the dataframe. (Feel free to make remarks about these outlier columns in the discussion, however!)
For the remaining features, are there any patterns in which columns have, or share, missing data?
# Perform an assessment of how much missing data there is in each column of the data
missing = azdias.isnull().sum().to_frame(name = 'missing_count')
missing['missing_per'] = missing['missing_count']/len(azdias.index)
missing.head(20)
missing[missing['missing_count'] >0].count()
Here, we see that there are 61 columns contain missing data.
# Investigate patterns in the amount of missing data in each column.
sns.distplot(missing['missing_per'], kde = False)
plt.title('Missing Percentage in Columns', fontsize=12)
plt.xlabel('Percentage of data missing', fontsize=10)
plt.ylabel('Frequency', fontsize=10)
We see that some columns have > 80% of data missing. We want to exclude those columns.
plt.figure(figsize=(15,8))
plt.xticks(rotation=90)
plt.title('Percentage of missing values in each column')
plot_order = missing['missing_per'].sort_values(ascending=False).index
sns.barplot(x= missing.index, y= missing['missing_per'], order = plot_order, color = 'g')
plt.xlabel('Column names')
plt.ylabel('Percentage')
plt.show()
#Find the column that missing values are greater than 30%
drop_col = missing[missing['missing_per'] > 0.3].index.tolist()
print(drop_col)
#Investigate the pattern of missing values
feat_info[feat_info['attribute'].isin(drop_col)]
# Remove the outlier columns from the dataset. (You'll perform other data
# engineering tasks such as re-encoding and imputation later.)
azdias = azdias.drop(drop_col,axis=1)
azdias.head()
We drop 6 columns, and 79 columns remaining.
(Double click this cell and replace this text with your own text, reporting your observations regarding the amount of missing data in each column. Are there any patterns in missing values? Which columns were removed from the dataset?)
We remove 6 columns that have more than 30% of data are missing to ensure our analytics quality later on.
The columns we drop include
Besides three columns are related to age, there isn't a specific pattern for columns we drop.
Now, you'll perform a similar assessment for the rows of the dataset. How much data is missing in each row? As with the columns, you should see some groups of points that have a very different numbers of missing values. Divide the data into two subsets: one for data points that are above some threshold for missing values, and a second subset for points below that threshold.
In order to know what to do with the outlier rows, we should see if the distribution of data values on columns that are not missing data (or are missing very little data) are similar or different between the two groups. Select at least five of these columns and compare the distribution of values.
countplot() function to create a bar chart of code frequencies and matplotlib's subplot() function to put bar charts for the two subplots side by side.Depending on what you observe in your comparison, this will have implications on how you approach your conclusions later in the analysis. If the distributions of non-missing features look similar between the data with many missing values and the data with few or no missing values, then we could argue that simply dropping those points from the analysis won't present a major issue. On the other hand, if the data with many missing values looks very different from the data with few or no missing values, then we should make a note on those data as special. We'll revisit these data later on. Either way, you should continue your analysis for now using just the subset of the data with few or no missing values.
# How much data is missing in each row of the dataset?
missing_row = azdias.isnull().sum(axis=1)
missing_row[:20]
plt.figure(figsize=(12,8))
sns.countplot(x=missing_row, color = 'g')
plt.xlabel('Numbers of missing columns')
plt.ylabel('Frequency')
plt.title('Missing rows count')
azdias['num_missing_row']= missing_row
#Divide the data into two subsets: one for data points that are above some threshold for missing values,
#and a second subset for points below that threshold.
#threshold = 20
many_missing_row = azdias[azdias['num_missing_row'] >= 10]
few_missing_row = azdias[azdias['num_missing_row'] < 10]
many_missing_row.shape, few_missing_row.shape
#Columns with no missing
missing[missing['missing_count'] == 0].index
# Compare the distribution of values for at least five columns where there are
# no or few missing values, between the two subsets.
fiv_col = ['ANREDE_KZ', 'FINANZ_MINIMALIST', 'GREEN_AVANTGARDE', 'SEMIO_DOM', 'ZABEOTYP', 'SEMIO_SOZ']
def compare_plot(col):
'''
input: column name:
output
'''
fig = plt.figure(figsize=(16,4))
ax1 = plt.subplot2grid((1,2), (0,0))
ax1.title.set_text('Many missing rows')
sns.countplot(many_missing_row[col])
ax2 = plt.subplot2grid((1,2), (0,1))
ax2.title.set_text('Few missing rows')
sns.countplot(few_missing_row[col])
plt.show()
for col in fiv_col:
compare_plot(col)
#only select rows with few missing values
azdias = few_missing_row
We can see missing data has a different distribution than non-missing data. Since a variable might relate to the distribution and the reason why the data are missing, we will want to consider missing data later on.
Checking for missing data isn't the only way in which you can prepare a dataset for analysis. Since the unsupervised learning techniques to be used will only work on data that is encoded numerically, you need to make a few encoding changes or additional assumptions to be able to make progress. In addition, while almost all of the values in the dataset are encoded using numbers, not all of them represent numeric values. Check the third column of the feature summary (feat_info) for a summary of types of measurement.
In the first two parts of this sub-step, you will perform an investigation of the categorical and mixed-type features and make a decision on each of them, whether you will keep, drop, or re-encode each. Then, in the last part, you will create a new data frame with only the selected and engineered columns.
Data wrangling is often the trickiest part of the data analysis process, and there's a lot of it to be done here. But stick with it: once you're done with this step, you'll be ready to get to the machine learning parts of the project!
# How many features are there of each data type?
feat_info['type'].value_counts()
For categorical data, you would ordinarily need to encode the levels as dummy variables. Depending on the number of categories, perform one of the following:
# Assess categorical variables: which are binary, which are multi-level, and
# which one needs to be re-encoded?
category_col = feat_info[feat_info['type'] == 'categorical']['attribute'].tolist()
category_col
#Print out numbers of the unquie columns if they are categorical and presented in azdias
for col in category_col:
if col in azdias.columns:
print(col, azdias[col].nunique())
# Re-encode categorical variable(s) to be kept in the analysis.
#create two lists, one stores multilevel categorical data, the other stores binary categorical data
multi_category = []
bi_category = []
for col in category_col:
if col in azdias.columns:
if azdias[col].nunique() > 2:
multi_category.append(col)
else:
bi_category.append(col)
print(multi_category)
print(bi_category)
#drop the columns that are multilevel categorical datat
azdias.drop(multi_category, axis=1, inplace=True)
#the binary variable that takes non-numeric values
print(azdias['ANREDE_KZ'].unique())
print(azdias['GREEN_AVANTGARDE'].unique())
print(azdias['SOHO_KZ'].unique())
print(azdias['VERS_TYP'].unique())
print(azdias['OST_WEST_KZ'].unique())
#re-encode binary columns
azdias['ANREDE_KZ'].replace([2,1], [1,0], inplace=True)
azdias['VERS_TYP'].replace([2.0,1.0], [1,0], inplace=True)
azdias['OST_WEST_KZ'].replace(['W','O'], [1,0], inplace=True)
#verify the result
print(azdias['ANREDE_KZ'].unique())
print(azdias['GREEN_AVANTGARDE'].unique())
print(azdias['SOHO_KZ'].unique())
print(azdias['VERS_TYP'].unique())
print(azdias['OST_WEST_KZ'].unique())
Excluding the variables we drop, there are 18 categorical variables, 13 of which are multilevel and 5 are binary. We drop the multilevel variables to keep our analysis more straightforward. In addition, we change all the binary variables into 1 and 0 so they can be used in the algorithm.
There are a handful of features that are marked as "mixed" in the feature summary that require special treatment in order to be included in the analysis. There are two in particular that deserve attention; the handling of the rest are up to your own choices:
Be sure to check Data_Dictionary.md for the details needed to finish these tasks.
# Investigate "PRAEGENDE_JUGENDJAHRE" and engineer two new variables.
azdias[['PRAEGENDE_JUGENDJAHRE']].head()
PRAEGENDE_JUGENDJAHRE
Dominating movement of person's youth (avantgarde vs. mainstream; east vs. west)
def define_decade(x):
if x in (1,2):
return 1
elif x in (3,4):
return 2
elif x in (5,6,7):
return 3
elif x in (8,9):
return 4
elif x in (10,11,12,13):
return 5
elif x in (14,15):
return 6
def define_movement(x):
if x in (2,4,6,7,9,11,13,15): #Avantgarde
return 0
elif x in (1,3,5,8,10,12,14): #Mainstream
return 1
#engineer two new variables: decade and movement
azdias['DECADES'] = azdias['PRAEGENDE_JUGENDJAHRE'].apply(define_decade)
azdias['MOVEMENTS'] = azdias['PRAEGENDE_JUGENDJAHRE'].apply(define_movement)
#drop the column
azdias.drop('PRAEGENDE_JUGENDJAHRE', axis=1, inplace=True)
# Investigate "CAMEO_INTL_2015" and engineer two new variables.
azdias[['CAMEO_INTL_2015']].head()
4.3. CAMEO_INTL_2015
German CAMEO: Wealth / Life Stage Typology, mapped to international code
# Adding a feature based on wealth
def cameo_wealth(x):
if x // 10 ==1: #Wealthy Households
return 1
if x // 10 ==2: #Prosperous Households
return 2
if x // 10 ==3: #Comfortable Households
return 3
if x // 10 ==4: #Less Affluent Households
return 4
if x // 10 ==5: #Poorer Households
return 5
# Adding a feature based on lfe stage
def cameo_life_stage(x):
if x % 10 ==1: #Pre-Family Couples & Singles
return 1
if x % 10 ==2: #Young Couples With Children
return 2
if x % 10 ==3: #Families With School Age Children
return 3
if x % 10 ==4: #Older Families & Mature Couples
return 4
if x % 10 ==5: #Elders In Retirement
return 5
azdias['CAMEO_INTL_2015'].dtypes #type is a string
#convert to numeric
azdias['CAMEO_INTL_2015'] = pd.to_numeric(azdias['CAMEO_INTL_2015'])
#engineer two new variables: wealth and life stage
azdias['WEALTH'] = azdias['CAMEO_INTL_2015'].apply(cameo_wealth)
azdias['LIFE_STAGE'] = azdias['CAMEO_INTL_2015'].apply(cameo_life_stage)
#drop the column
azdias.drop('CAMEO_INTL_2015', axis=1, inplace=True)
For variable PRAEGENDE_JUGENDJAHRE, we re-engineer it into two variables
We drop PRAEGENDE_JUGENDJAHRE, and create two new variables DECADE and MOVEMENTS.
For variable CAMEO_INTL_2015, we re-engineer it into two variables
We drop CAMEO_INTL_2015, and create two new variables WEALTH and LIFE_STAGE.
In order to finish this step up, you need to make sure that your data frame now only has the columns that you want to keep. To summarize, the dataframe should consist of the following:
Make sure that for any new columns that you have engineered, that you've excluded the original columns from the final dataset. Otherwise, their values will interfere with the analysis later on the project. For example, you should not keep "PRAEGENDE_JUGENDJAHRE", since its values won't be useful for the algorithm: only the values derived from it in the engineered features you created should be retained. As a reminder, your data should only be from the subset with few or no missing values.
# If there are other re-engineering tasks you need to perform, make sure you
# take care of them here. (Dealing with missing data will come in step 2.1.)
for col in azdias.columns:
print(col, azdias[col].dtypes)
azdias.drop('num_missing_row', axis=1, inplace=True)
# Do whatever you need to in order to ensure that the dataframe only contains
# the columns that should be passed to the algorithm functions.
azdias.isnull().sum()/len(azdias) #double check missing columns
azdias.isnull().sum(axis=1) #double check missing rows
Even though you've finished cleaning up the general population demographics data, it's important to look ahead to the future and realize that you'll need to perform the same cleaning steps on the customer demographics data. In this substep, complete the function below to execute the main feature selection, encoding, and re-engineering steps you performed above. Then, when it comes to looking at the customer data in Step 3, you can just run this function on that DataFrame to get the trimmed dataset in a single step.
def clean_data(df):
"""
Perform feature trimming, re-encoding, and engineering for demographics
data
INPUT: Demographics DataFrame
OUTPUT: Trimmed and cleaned demographics DataFrame
"""
# Put in code here to execute all main cleaning steps:
# 1. convert missing value codes into NaNs
columns = df.columns
for col in columns:
missing = feat_info[feat_info['attribute'] == col]['missing_or_unknown']
#change the panda series into a string
missing_str = missing.to_string(index = False).strip('[]')
if missing_str != '':
#change the string into a list
missing_list =[x if x in ['X','XX'] else int(x) for x in missing_str.split(',')]
#replace missing values in missing_list with nan
df[col] = df[col].replace(missing_list, np.nan)
# 2. remove selected columns and rows
# remove selected columns
drop_col = ['AGER_TYP', 'GEBURTSJAHR', 'TITEL_KZ', 'ALTER_HH', 'KK_KUNDENTYP', 'KBA05_BAUMAX']
df = df.drop(drop_col,axis=1)
#find missing rows
missing_row = df.isnull().sum(axis=1)
df['num_missing_row']= missing_row
# remove missing rows
many_missing_row = df[df['num_missing_row'] >= 10]
few_missing_row = df[df['num_missing_row'] < 10]
print(f'{len(many_missing_row)} rows have many missing data')
#few missing row as the new df
df = few_missing_row
df.drop('num_missing_row', axis=1, inplace=True)
print(f'Total rows in dataset is {df.shape[0]}')
#find multilevel categorical variables and drop it
multi_category = []
bi_category = []
for col in category_col:
if col in df.columns:
if df[col].nunique() > 2:
multi_category.append(col)
else:
bi_category.append(col)
df.drop(multi_category, axis=1, inplace=True)
# encoding the 'OST_WEST_KZ' binary categorical column
df['OST_WEST_KZ'].replace(['W','O'], [1,0], inplace=True)
# Engineering(converting) "PRAEGENDE_JUGENDJAHRE" and 'CAMEO_INTL_2015'into two new variables each
# adding 2 new columns "DECADES" and 'MOVEMENTS' based on decade of birth and movement
df['DECADES'] = df['PRAEGENDE_JUGENDJAHRE'].apply(define_decade)
df['MOVEMENTS'] = df['PRAEGENDE_JUGENDJAHRE'].apply(define_movement)
# Dropping 'PRAEGENDE_JUGENDJAHRE' column from the dataframe
df = df.drop('PRAEGENDE_JUGENDJAHRE',axis=1)
# Adding 2 new features based on wealth and life stage and dropping 'CAMEO_INTL_2015'
df['CAMEO_INTL_2015'] = pd.to_numeric(df['CAMEO_INTL_2015'])
#engineer two new variables: wealth and life stage
df['WEALTH'] = df['CAMEO_INTL_2015'].apply(cameo_wealth)
df['LIFE_STAGE'] = df['CAMEO_INTL_2015'].apply(cameo_life_stage)
df.drop('CAMEO_INTL_2015', axis=1, inplace=True)
# Return the cleaned dataframe.
return df
Before we apply dimensionality reduction techniques to the data, we need to perform feature scaling so that the principal component vectors are not influenced by the natural differences in scale for features. Starting from this part of the project, you'll want to keep an eye on the API reference page for sklearn to help you navigate to all of the classes and functions that you'll need. In this substep, you'll need to check the following:
.fit_transform() method to both fit a procedure to the data as well as apply the transformation to the data at the same time. Don't forget to keep the fit sklearn objects handy, since you'll be applying them to the customer demographics data towards the end of the project.# copying azdias
azdias_copy = azdias.copy()
columns = azdias_copy.columns
#Test of how to use imputer
imp_mean = Imputer(missing_values=np.nan, strategy='mean', axis = 0)
imp_mean.fit_transform([[7, 2, 3], [4, np.nan, 6], [10, 5, 9]])
#impute the data by mean
imputer = Imputer(strategy='mean', axis=0)
azdias_copy = imputer.fit_transform(azdias_copy)
#convert the array back to dataframe
azdias_copy = pd.DataFrame(azdias_copy, columns = columns)
azdias_copy.isnull().sum()
# Apply feature scaling to the general population demographics data.
scaler = StandardScaler()
azdias_scaled = scaler.fit_transform(azdias_copy)
azdias_scaled = pd.DataFrame(azdias_scaled, columns= columns)
azdias_scaled.head()
We copy the data frame and impute the mean for the missing data. The reason to impute data is to decrease information loss when deleting them. Yet, we might suffer some inaccuracy from imputation. As for StandardScaler, we decide to use it to create an isotropic dataset by reducing the variance of variables. The reason for choosing standardization over other methods is because the K-means clustering we will perform is isotropic in all directions of space so we prefer round than elongated clusters. StandardScaler gives equal importance to every variable.
On your scaled data, you are now ready to apply dimensionality reduction techniques.
plot() function. Based on what you find, select a value for the number of transformed features you'll retain for the clustering part of the project.# Apply PCA to the data.
all_components = len(columns)
pca_model = PCA(all_components)
pca_features = pca_model.fit_transform(azdias_scaled)
# Investigate the variance accounted for by each principal component.
pca_features.shape
print(len(pca_model.explained_variance_ratio_))
print(pca_model.explained_variance_ratio_)
#Accumulative sum of explain variance ration
np.cumsum(pca_model.explained_variance_ratio_)
If we have every variable as our component, there is very small explanation of variance for each component.
# Re-apply PCA to the data while selecting for number of components to retain.
def scree_plot(pca): #from Udacity notes
'''
Creates a scree plot associated with the principal components
INPUT: pca - the result of instantian of PCA in scikit learn
OUTPUT:
None
'''
num_components = len(pca.explained_variance_ratio_)
ind = np.arange(num_components)
vals = pca.explained_variance_ratio_
plt.figure(figsize=(18, 10))
ax = plt.subplot(111)
cumvals = np.cumsum(vals)
ax.bar(ind, vals)
ax.plot(ind, cumvals)
for i in range(num_components):
ax.annotate(r"%s%%" % ((str(vals[i]*100)[:4])), (ind[i]+0.2, vals[i]), va="bottom", ha="center", fontsize= 5)
ax.xaxis.set_tick_params(width=0)
ax.yaxis.set_tick_params(width=2, length=12)
ax.set_xlabel("Principal Component")
ax.set_ylabel("Variance Explained (%)")
plt.title('Explained Variance Per Principal Component')
scree_plot(pca_model)
#Reapply PCA with 25 components
pca_model_25 = PCA(25)
pca_features_25 = pca_model_25.fit_transform(azdias_scaled)
print(pca_features_25.shape)
print(np.cumsum(pca_model_25.explained_variance_ratio_))
scree_plot(pca_model_25)
We apply PCA() method to the scaled dataset by observing the scree plot with accumulated explained variance. Here, we see that with 25 components, it accounts for around 83% of the variance. Therefore, we choose to use 25 components for clustering.
Now that we have our transformed principal components, it's a nice idea to check out the weight of each variable on the first few components to see if they can be interpreted in some fashion.
As a reminder, each principal component is a unit vector that points in the direction of highest variance (after accounting for the variance captured by earlier principal components). The further a weight is from zero, the more the principal component is in the direction of the corresponding feature. If two features have large weights of the same sign (both positive or both negative), then increases in one tend expect to be associated with increases in the other. To contrast, features with different signs can be expected to show a negative correlation: increases in one variable should result in a decrease in the other.
def pca_results(full_dataset, pca):
'''
Create a DataFrame of the PCA results
Includes dimension feature weights and explained variance
Visualizes the PCA results
'''
# Dimension indexing
#use the number of componenets to create dimensions
dimensions = dimensions = ['Dimension {}'.format(i) for i in range(1,len(pca.components_)+1)]
# use PCA components to create a dataframe: columns = variables, rows = component values
components = pd.DataFrame(np.round(pca.components_, 4), columns = full_dataset.columns)
components.index = dimensions#change index to dimensions
# PCA explained variance
ratios = pca.explained_variance_ratio_.reshape(len(pca.components_), 1)
#make explained variance into a column format
variance_ratios = pd.DataFrame(np.round(ratios, 4), columns = ['Explained Variance'])
variance_ratios.index = dimensions
return pd.concat([variance_ratios, components], axis = 1) #put explained variance and component df together
def pca_plot(pca_results_df , nth_component):
explain_variance = pca_results_df['Explained Variance'][:nth_component]
accu_explain_variance = np.round(explain_variance.sum(),4)
sort_comp = pca_results_df.iloc[nth_component-1].sort_values()
head = sort_comp[:5] #largest five variables in a component
tail = sort_comp[-5:] #smallest five variables in a component
components = pd.concat([head, tail])
# Plot the components
components.plot(kind='bar', title='Component ' + str(nth_component), color = 'c')
ax = plt.gca()
ax.grid(linewidth='0.5', alpha=0.5)
plt.show()
print('Accumulative explained varaince for Component',nth_component,'is',accu_explain_variance)
return components
pca_results_25 = pca_results(azdias_scaled, pca_model_25)
pca_results_25
pca_plot(pca_results_25, 1)
pca_plot(pca_results_25, 2)
pca_plot(pca_results_25, 3)
We look into the top three components and analyze what it stands for.
For Component 1, its positive values related to PLZ8 indicate more members in the family. Wealth and household net income are both positive and related to financial conditions. It describes people who live in a big family with lower income. In contrast, strong negative values such as PLZ8_ANTG1, KBA05_ANTG1, and FINANZ_MINIMALIST indicate smaller family capacity with more financial affluence.
We see that Component 1 is related to the size of the household and financial condition.
As for Component 2, positive values are related to age and conservative personality. It describes old people as being less event-oriented, less sensual-minded, less prepared in finance, and a conservative shopper. As for negative values, it describes a liberal personality that young people being less religious, less traditional, less dutiful, less traditional-minded, and unlikely to save money.
We see that Component 2 is related to age and liberal/conservative personality.
As for Component 3, besides age, positive values have a strong association with characteristics of a people person, such as social, family, and culture. The positive values describe males that are less dreamful, less social, less family-oriented, and conservative return shopping type. They are not financial minimalists. Negative values are related to personalities that describe a person as being less critical, less rational, and less dominant. Females that are less dominant-minded, less critical-minded, less rational have less combative attitude.
We see that Component 3 is related to gender, and social/logical personality.
You've assessed and cleaned the demographics data, then scaled and transformed them. Now, it's time to see how the data clusters in the principal components space. In this substep, you will apply k-means clustering to the dataset and use the average within-cluster distances from each point to their assigned cluster's centroid to decide on a number of clusters to keep.
.score() method might be useful here, but note that in sklearn, scores tend to be defined so that larger is better. Try applying it to a small, toy dataset, or use an internet search to help your understanding.from tqdm import tqdm
from sklearn.cluster import MiniBatchKMeans
# Over a number of different cluster counts
n_clusters = list(range(1,30))
scores = []
# run k-means clustering on the data and...
for cluster in tqdm(n_clusters):
kmeans = MiniBatchKMeans(n_clusters = cluster)
model = kmeans.partial_fit(pca_features_25)
# compute the average within-cluster distances.
score = np.abs(model.score(pca_features_25))
scores.append(score)
# Investigate the change in within-cluster distance across number of clusters.
# HINT: Use matplotlib's plot function to visualize this relationship.
plt.plot(n_clusters, scores, linestyle='--', marker='o', color='b');
plt.xlabel('K')
plt.ylabel('SSE')
plt.title('SSE vs. K')
# Re-fit the k-means model with the selected number of clusters and obtain
# cluster predictions for the general population demographics data.
kmeans = KMeans(n_clusters = 7)
kmodel_7 = kmeans.fit(pca_features_25)
predict_general = kmodel_7.predict(pca_features_25)
predict_general, len(predict_general)
(unique, counts) = np.unique(predict_general, return_counts=True)
print(unique,counts)
general_dis = pd.concat([pd.Series(unique, name='Cluster'), pd.Series(counts, name = 'Count General')], axis=1)
Since KMeans take too much time, we perform MiniBatchKMeans clustering into the 25 features we create. Observing the distance to the centroid curve, we can see that the elbow point can be inferred as 7 and we can use 7 as the number of clusters on the transformed demographics data.
Now that you have clusters and cluster centers for the general population, it's time to see how the customer data maps on to those clusters. Take care to not confuse this for re-fitting all of the models to the customer data. Instead, you're going to use the fits from the general population to clean, transform, and cluster the customer data. In the last step of the project, you will interpret how the general population fits apply to the customer data.
;) delimited.clean_data() function you created earlier. (You can assume that the customer demographics data has similar meaning behind missing data patterns as the general demographics data.).fit() or .fit_transform() method to re-fit the old objects, nor should you be creating new sklearn objects! Carry the data through the feature scaling, PCA, and clustering steps, obtaining cluster assignments for all of the data in the customer demographics data.# Load in the customer demographics data.
customers = pd.read_csv('Udacity_CUSTOMERS_Subset.csv', sep = ';')
customers_clean = clean_data(customers)
customers_clean.head()
# Compare columns from general data to customers data
list(set(azdias.columns) - set(customers_clean))
# Apply preprocessing, feature transformation, and clustering from the general
# demographics onto the customer data, obtaining cluster predictions for the
# customer demographics data.
#copy df
customers_copy = customers_clean.copy()
#impute data for nan
imputer = Imputer(strategy='mean', axis=0)
customers_copy = imputer.fit_transform(customers_copy)
customers_copy = pd.DataFrame(customers_copy, columns = columns)
#standerdize dataframe
customers_copy = scaler.transform(customers_copy)
customers_copy = pd.DataFrame(customers_copy, columns= columns)
customers_copy.head()
#Use our pca model with 25 components to fit general data
pca_customers = pca_model_25.transform(customers_copy)
#Use Kmeans model with 7 clusters to predict
predict_customers = kmodel_7.predict(pca_customers)
pca_customers
predict_customers
pca_customers_df = pd.DataFrame(pca_customers, columns=np.arange(1, 26))
pca_customers_df.head()
(unique, counts) = np.unique(predict_customers, return_counts=True)
print(unique,counts)
customer_dis = pd.concat([pd.Series(unique, name='Cluster'), pd.Series(counts, name = 'Count Customer')], axis=1)
# customer_dis['Dist General'] = customer_dis['Count General']/customer_dis['Count General'].sum()
customer_dis
At this point, you have clustered data based on demographics of the general population of Germany, and seen how the customer data for a mail-order sales company maps onto those demographic clusters. In this final substep, you will compare the two cluster distributions to see where the strongest customer base for the company is.
Consider the proportion of persons in each cluster for the general population, and the proportions for the customers. If we think the company's customer base to be universal, then the cluster assignment proportions should be fairly similar between the two. If there are only particular segments of the population that are interested in the company's products, then we should see a mismatch from one to the other. If there is a higher proportion of persons in a cluster for the customer data compared to the general population (e.g. 5% of persons are assigned to a cluster for the general population, but 15% of the customer data is closest to that cluster's centroid) then that suggests the people in that cluster to be a target audience for the company. On the other hand, the proportion of the data in a cluster being larger in the general population than the customer data (e.g. only 2% of customers closest to a population centroid that captures 6% of the data) suggests that group of persons to be outside of the target demographics.
Take a look at the following points in this step:
countplot() or barplot() function could be handy..inverse_transform() method of the PCA and StandardScaler objects to transform centroids back to the original data space and interpret the retrieved values directly.# Compare the proportion of data in each cluster for the customer data to the
# proportion of data in each cluster for the general population.
dist = pd.merge(general_dis, customer_dis, on='Cluster')
#assign rows with lots of missing value as Cluster -1
missing_row = {'Cluster': -1, 'Count General':len(many_missing_row), 'Count Customer':55493}
#add numbers of missing rows in the distribution
dist = dist.append(missing_row, ignore_index = True)
dist['Dist General'] = dist['Count General']/dist['Count General'].sum()
dist['Dist Customer'] = dist['Count Customer']/dist['Count Customer'].sum()
dist.index = ['Cluster 0', 'Cluster 1', 'Cluster 2', 'Cluster 3', 'Cluster 4','Cluster 5','Cluster 6','Cluster -1']
# dist.index = ['Cluster 0', 'Cluster 1', 'Cluster 2', 'Cluster 3', 'Cluster -1']
dist
fig, ax = plt.subplots(figsize=(8,4))
bar_width = 0.35
index = np.arange(8)
gen = plt.bar(index, dist['Dist General'], bar_width,
color='orange',
label='General Population')
cust = plt.bar(index + bar_width, dist['Dist Customer'], bar_width,
color='c',
label='Customer Data')
ax.set_ylabel('Proportion(%)')
ax.set_title('Proportions per cluster for general vs customer populations')
plt.legend(('General prop', 'Customer prop %'),fontsize=10)
plt.xticks(index + bar_width/2, dist.index)
plt.xticks(rotation = 360)
dist['Dist Customer'] - dist['Dist General']
Cluster 5 and missing data are overrepresented, while Cluster 0 and Cluster 6 are underrepresented.
# What kinds of people are part of a cluster that is overrepresented or underrepresented in the
# customer data compared to the general population?
# scaler.inverse_transform(pca_model_25.inverse_transform(pca_customers[np.where(predict_customers ==5)])).round(1)
# Over represented group: Let's look at cluster 5
over_represent = scaler.inverse_transform(pca_model_25.inverse_transform(kmodel_7.cluster_centers_[5]))
over_represent_features = pd.Series(over_represent, index = azdias_copy.columns)
over_represent_features.sort_values(ascending = False).head()
over_represent_features.sort_values(ascending = False).tail(5)
# Under represented group: Let's look at cluster 6
under_represent = scaler.inverse_transform(pca_model_25.inverse_transform(kmodel_7.cluster_centers_[6]))
under_represent_features = pd.Series(under_represent, index = azdias_copy.columns)
under_represent_features.sort_values(ascending = False).head()
# Under represented group: Let's look at cluster 0
under_represent = scaler.inverse_transform(pca_model_25.inverse_transform(kmodel_7.cluster_centers_[0]))
under_represent_features = pd.Series(under_represent, index = azdias_copy.columns)
under_represent_features.sort_values(ascending = False).head()
under_represent_features.sort_values(ascending = False).tail()
#add cluster number back to pca data
pca_customers_df['cluster'] = predict_customers
pca_customers_df.head()
sns.pairplot(pca_customers_df,
vars = np.arange(1, 6),
diag_kind = 'kde',
hue="cluster",
palette="Paired");
sns.pairplot(pca_customers_df,
vars = np.arange(6, 11),
diag_kind = 'kde',
hue="cluster",
palette="Paired");
sns.pairplot(pca_customers_df,
vars = np.arange(11, 16),
diag_kind = 'kde',
hue="cluster",
palette="Paired");
sns.pairplot(pca_customers_df,
vars = np.arange(16, 21),
diag_kind = 'kde',
hue="cluster",
palette="Paired");
sns.pairplot(pca_customers_df,
vars = np.arange(21, 26),
diag_kind = 'kde',
hue="cluster",
palette="Paired");
def map_kmeans_weights_to_feats(kmeans, df, nth_cluster):
'''Map pca weights to individual features
and return two pd.Series on with the highest
positive weights and one with the lowest negative
weights'''
weights = pd.DataFrame(np.round(kmeans.cluster_centers_, 4), columns= df.keys())
centroid = weights.iloc[nth_cluster, :]
cent_pos = centroid[centroid > 0].sort_values(ascending=False)
cent_neg = centroid[centroid < 0].sort_values(ascending=True)
return cent_pos, cent_neg
# Over represented group: Let's look at cluster 5
positive, negative = map_kmeans_weights_to_feats(kmodel_7, pca_customers_df.iloc[:, :-1], 5)
from IPython.core.display import HTML
def create_bar_table(comp_pos, comp_neg):
'''Create and display a conditionally styled pandas dataframe
for the interpertation of the positive and negative weights
of PCA and centroid distances for KMeans'''
head = """
<table>
"""
row = ""
for serie in [comp_pos[:15],comp_neg[:15]]:
s = serie.copy()
s.name=''
row += "<td>{}</td>".format(s.to_frame().style.bar(
align='mid',
color=['#d65f5f', '#5fba7d'],
width=100).render()
)
row += '</tr>'
head += row
head+= """
</table>"""
display(HTML(head))
create_bar_table(positive, negative)
Citation: for map_kmeans_weights_to_feats and create_bar_table, I follow the code here
We can see that we have a large proportion of missing data in customer data than general demographic data, which might due to limitations during the data collection process. Comparing the proportion of clusters in the two data, we see that Cluster 5 is overrepresented in the customer data, while Cluster 0 and Cluster 6 are underrepresented.
Significant variables in Cluster 5 include MIN_GEBAEUDEJAHR, KBA13_ANZAHL_PKW, LP_LEBENSPHASE_FEIN, which represent First-year building, numbers of cars, and life stage of a person. It is so weird because they are similar to the variables we find in Cluster 0 and 6. And I don't know how to interpret these three variables.
Therefore, I try to use a pair plot and interpret the cluster through components. I learn map_kmeans_weights_to_feats to produce important components for Cluster 5. It shows that Component 3 is the most positive and Component 1 is the most negative. This indicates they are males that are less dreamful, less social, less family-oriented, and they are conservative return shopping type. They have a smaller family capacity with decent financial affluence.
Congratulations on making it this far in the project! Before you finish, make sure to check through the entire notebook from top to bottom to make sure that your analysis follows a logical flow and all of your findings are documented in Discussion cells. Once you've checked over all of your work, you should export the notebook as an HTML document to submit for evaluation. You can do this from the menu, navigating to File -> Download as -> HTML (.html). You will submit both that document and this notebook for your project submission.